import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  ssoLogin,
  getUserInfo,
  validateTicket,
} from '@/api/security';
import { LoginInfo } from '@/api/model/securityModel';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    username: undefined,
    userCode: undefined,
    avatar: undefined,
    deptCode: undefined,
    address: undefined,
    email: undefined,
    deptId: undefined,
    mobile: undefined,
    title: undefined,
    // 密级
    secretLevel: undefined,
    role: '',
    // 路由权限
    menus: [],
    // 按钮权限
    permissions: [],
    roles: [],
    mainOrgId: undefined, // 主职的组织机构id
    mainDept: undefined, // 主职部门，是个对象
    currentOrgId: undefined, // 当前选择的组织机构id
    currentDeptId: undefined, // 当前选择的部门id
    orgInfoList: [], // 所属的组织机构List
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const { data } = await getUserInfo();

      this.setInfo({
        ...data.user,
        menus: data.menus,
        roles: data.roles,
        permissions: data.permissions,
      });
    },

    // Login
    async login(loginForm: LoginInfo) {
      try {
        const { data } = await userLogin(loginForm);
        setToken(data.access_token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    // sso Login
    async ssoLogin(token: string) {
      try {
        const { data } = await ssoLogin(token);
        setToken(data.access_token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    // token Login
    async tokenLogin(token: string) {
      try {
        setToken(token); // 这里拿到了token直接就存起来
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    // ticket Login
    async ticketLogin(ticket: string) {
      try {
        const { data } = await validateTicket(ticket);
        if (data !== null) {
          setToken(data.access_token);
        } else {
          clearToken();
        }
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
